package com.sxg.security.service;

import com.sxg.entity.SxgUserEntity;
import com.sxg.security.pojo.LoginUser;
import com.sxg.service.SxgUserService;
import com.sxg.utils.MessageUtils;
import com.sxg.utils.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.security.core.userdetails.UserDetailsService;
import org.springframework.security.core.userdetails.UsernameNotFoundException;
import org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder;
import org.springframework.stereotype.Service;

/**
 * 用户验证处理
 *
 * @author ruoyi
 */
@Service
public class UserDetailsServiceImpl implements UserDetailsService {
    private static final Logger log = LoggerFactory.getLogger(UserDetailsServiceImpl.class);

    @Autowired
    private SxgUserService userService;

    @Override
    public UserDetails loadUserByUsername(String username) throws UsernameNotFoundException {
        SxgUserEntity user = null;
        try {
            user = userService.selectUserByUserName(Long.valueOf(username));
        } catch (NumberFormatException e) {
            throw new RuntimeException("邮箱格式错误");
        }
        if (StringUtils.isNull(user)) {
            log.info("登录用户：{} 不存在.", username);
            throw new RuntimeException("用户不存在");
        } else if ("1".equals(user.getStatus())) {
            log.info("登录用户：{} 已被停用.", username);
            throw new RuntimeException("该账号已停用");
        }

        return createLoginUser(user);
    }

    public UserDetails createLoginUser(SxgUserEntity user) {
        LoginUser loginUser = new LoginUser();
        loginUser.setSxgUserEntity(user);
        return loginUser;
    }

    public static void main(String[] args) {
        BCryptPasswordEncoder bCryptPasswordEncoder = new BCryptPasswordEncoder();
        String admin = bCryptPasswordEncoder.encode("admin");
        System.out.println(admin);
    }

}
